package com.anpy.anlibrary.net

import com.anpy.anlibrary.contants.LibConstants
import com.anpy.anlibrary.net.common.launchIO
import com.anpy.anlibrary.net.common.launchUI
import com.anpy.anlibrary.net.common.parseObject
import com.anpy.anlibrary.net.common.toJsonObject
import kotlinx.coroutines.Job
import kotlinx.coroutines.suspendCancellableCoroutine
import okhttp3.Response

fun http(config: NetWrapper<String>.() -> Unit): Job {
    val wrapper = NetWrapper<String>()
    wrapper.config()
    with(wrapper) {
        return launchIO {
            var result: String? = null
            var error: String? = null
            try {
                val response = HTTP.execute(method, url, params, appName)
                if (response.isSuccessful) {
                    result = response.body()!!.string().trim()
                } else {
                    error = "code:${response.code()} ; 连接错误:${response.errorBody()!!.string()}"
                }
            } catch (e: Exception) {
                error = "错误:${e.message}"
            }
            launchUI {
                result?.let {
                    onSuccess(it)
                }
                error?.let {
                    onError(it)
                }
            }.join()
        }
    }
}

/**
 * 上传文件参数必须为File类型或者string类型
 */
inline fun <reified T> httpBase(config: NetWrapper<T>.() -> Unit) =
    httpBase(Settings.objectStyle(), config)

inline fun <reified T> httpBase(style: JsonStyle?, config: NetWrapper<T>.() -> Unit): Job {
    if (style == null) throw IllegalArgumentException("http请求解析成指定的实体类必须指定JsonStyle!!!")
    val wrapper = NetWrapper<T>()
    wrapper.config()
    with(wrapper) {
        return launchIO {
            var result: T? = null
            var error: String? = null
            var responseError: String? = null
            suspendCancellableCoroutine<Response> {
                try {
                    val response = HTTP.execute(method, url, params, appName)
                    if (response.isSuccessful) {
                        val json = response.body()!!.string().trim().toJsonObject()
                        var dataString = ""
                        if (!json.isNull(style.result)) {
                            dataString = json.getString(style.result).trim()
                        }
                        if (!json.isNull(style.code)) {
                            dataString = json.getString(style.code).trim()
                        }
                        if (LibConstants.REQUEST_RESULT_SUCCESS == dataString || LibConstants.REQUEST_CODE_SUCCESS == dataString) {
                            result = json.toString()
                                .parseObject<T>()
                        } else {
                            result = null
                            responseError = json.getString("msg")
                        }
                    } else {
                        error = "code:${response.code()} ; 连接错误:${response.errorBody()!!.string()}"
                    }
                } catch (e: Exception) {
                    error = "错误:${e.message}"
                }

                launchUI {
                    result?.let { it -> onSuccess(it) }
                    responseError?.let { it -> onResponseError(it) }
                    error?.let {
                        onError(it)
                    }
                }
            }
        }
    }
}